<template>
  <div class="bigbox">
    <div class="common-header">
      <div class="pageTitle">项目运营信息表档案</div>
      <div>
        <el-button type="primary" size="small" @click="exp">导出模板</el-button>
        <el-button type="primary" size="small" @click="edit">编辑</el-button>
      </div>
    </div>
    <div style="margin: 20px; margin-top: 60px">
      <OperationCommon ref="common" :columns="tableColumn" />
    </div>
  </div>
</template>
<script>
import OperationCommon from './common.vue';
import * as ExcelJS from 'exceljs';
export default {
  components: { OperationCommon },
  data() {
    return {
      atozStr: 'ABCDEFGHI',
      atozArr: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
      tableColumn: [
        // {
        //   width: 60,
        //   slots: {
        //     default: () => {
        //       return [
        //         <span class="drag-btn">
        //           <i class="vxe-icon-menu"></i>
        //         </span>,
        //       ];
        //     },
        //     header: () => {
        //       return [
        //         <vxe-tooltip v-model={this.showHelpTip2} content="按住后可以上下拖动排序！" enterable>
        //           <i
        //             class="vxe-icon-question-circle-fill"
        //             onClick={() => {
        //               this.showHelpTip2 = !this.showHelpTip2;
        //             }}
        //           ></i>
        //         </vxe-tooltip>,
        //       ];
        //     },
        //   },
        // },
        // {
        //   field: 'icon',
        //   treeNode: true,
        //   slots: { default: 'icon_default' },
        // },
        {
          field: 'field',
          title: '字段',
          treeNode: true,
          editRender: {},
          slots: { default: 'field_default' },
        },
        // { field: 'status', title: '状态', editRender: {}, slots: { edit: 'status_edit', default: 'status_default' } },
        {
          field: 'type',
          title: '对应自定义档案',
          editRender: {},
          slots: { default: 'type_default' },
        },
        {
          field: 'lineNumber',
          title: '行号',
          editRender: {},
          slots: { default: 'lineNumber_default' },
        },
        {
          field: 'startColumn',
          title: '开始列',
          editRender: {},
          slots: { default: 'startColumn_default' },
        },
        {
          field: 'endColumn',
          title: '结束列',
          editRender: {},
          slots: { default: 'endColumn_default' },
        },
      ],
      templateData: [],
      newTable: [],
      mergeCells: [],
    };
  },
  created() {
    this.$api.ApiOperationalTemplateExport().then((res) => {
      this.templateData = this.tranform([{ name: '表头', value: '项目运营相关信息表' }, ...res.data]);
    });
  },
  methods: {
    edit() {
      this.$router.push('/operationEdit');
    },
    tranform(tableData) {
      const table = tableData.map((item) => {
        if (!item.children || item.children.length === 0) {
          return item;
        } else {
          return item.children?.reduce((prev, cur) => {
            const last = prev[prev.length - 1];
            if (last?.lineNumber === cur.lineNumber) {
              last.children.push(cur);
            } else {
              prev.push({
                ...item,
                lineNumber: cur.lineNumber,
                children: [
                  {
                    ...cur,
                  },
                ],
              });
            }
            return prev;
          }, []);
        }
      });
      this.newTable = [];
      let start = 0;
      table.flat(1).forEach((item, i) => {
        if (item.name === '表头') {
          this.newTable.push({ A: item.value });
          this.mergeCells.push({
            row: 0,
            col: 0,
            rowspan: 1,
            colspan: 9,
          });
        } else {
          this.newTable.push({ A: item.name });

          if (this.newTable[start]['A'] !== item.name) {
            if (start !== 0) {
              this.mergeCells.push({
                row: start,
                col: 0,
                rowspan: i - start,
                colspan: 1,
              });
            }
            start = i;
          }
          this.mergeCells.push({
            row: start,
            col: 0,
            rowspan: i - start + 1,
            colspan: 1,
          });
          let last = this.newTable[this.newTable.length - 1];
          this.newTable[this.newTable.length - 1] = {
            ...last,
            ...item.children?.reduce((prev, cur) => {
              prev[this.atozArr[cur.startColumn - 1]] = cur.name;
              prev[this.atozArr[cur.startColumn]] = cur.value;
              // 合并列
              this.mergeCells.push({
                row: cur.lineNumber,
                col: cur.startColumn,
                rowspan: 1,
                colspan: cur.endColumn - cur.startColumn,
              });
              return prev;
            }, {}),
          };
        }
      });
      return table.flat(1);
    },
    exp() {
      const workbook = new ExcelJS.Workbook();
      const sheet = workbook.addWorksheet('项目运营相关信息表', {
        properties: { defaultRowHeight: 30, defaultColWidth: 25 },
      });
      const atoi = this.atozArr;
      sheet.columns = atoi.map((key) => {
        return {
          header: key,
          key: key,
          width: '25',
        };
      });
      const fixedRow = 1;
      sheet.spliceRows(0, 1);
      this.templateData.forEach((item, i) => {
        if (item.name === '表头') {
          sheet.insertRow(1, this.newTable[i]);
        } else {
          sheet.insertRow(item.children ? item.children[0].lineNumber + fixedRow : null, this.newTable[i]);
        }
      });
      sheet.eachRow((row) => {
        row.alignment = { wrapText: true, vertical: 'middle', horizontal: 'center' };
        row._cells.forEach((item) => {
          item.border = {
            top: { style: 'thin', color: { argb: '000000' } },
            left: { style: 'thin', color: { argb: '000000' } },
            bottom: { style: 'thin', color: { argb: '000000' } },
            right: { style: 'thin', color: { argb: '000000' } },
          };
        });
        row.eachCell((cell) => {
          cell ? cell : {};
          cell.fill = {
            type: 'pattern',
            pattern: 'thin',
            fgColor: { argb: 'FF000000' },
            vertical: 'middle',
            horizontal: 'center',
          };
          cell.font = {
            color: { argb: 'FF000000' },
            name: 'Calibri',
            family: 2,
            scheme: 'minor',
          };
          cell.alignment = { wrapText: true, vertical: 'middle', horizontal: 'center' };
        });
      });
      // 合并单元格
      const transformRow = (list) => {
        let start = 0;
        while (start < list.length) {
          const first = list[start];
          if (!first) {
            start++;
            continue;
          }
          const last = list.lastIndexOf(first);
          if (start !== last) {
            sheet.mergeCells(`A${start + fixedRow}:A${last + fixedRow}`);
          }
          start = last + 1;
        }
      };
      const transformColumn = (list) => {
        let start = 0;
        while (start < list.length) {
          if (list[start].name === '表头') {
            sheet.mergeCells('A1:I1');
            sheet.getCell(`A1`).alignment = { vertical: 'middle', horizontal: 'center' };
          } else {
            list[start].children &&
              list[start].children.forEach((it) => {
                const start = this.atozArr[it.startColumn];
                const end = this.atozArr[it.endColumn - 1];
                sheet.mergeCells(`${start}${it.lineNumber + fixedRow}:${end}${it.lineNumber + fixedRow}`);
                if (it.name.includes('日期') || it.name.includes('时间')) {
                  sheet.getCell(`${start}${it.lineNumber + fixedRow}`).dataValidation = {
                    type: 'date',
                    operator: 'lessThan',
                    showErrorMessage: true,
                    allowBlank: true,
                  };
                }
                // 添加下拉列表验证规则
                it.options &&
                  (sheet.getCell(`${start}${it.lineNumber + fixedRow}`).dataValidation = {
                    type: 'list',
                    allowBlank: true,
                    formulae: ['"' + it.options + '"'],
                  });
              });
          }
          start++;
        }
      };
      const AList = [];
      this.templateData.forEach((item) => {
        if (item.name !== '表头') {
          if (!item.children || item.children.length === 0) {
            AList[item.lineNumber] = item.name;
          } else {
            const child = item.children[0];
            AList[child.lineNumber] = item.name;
          }
        }
      });
      transformRow(AList);

      transformColumn(this.templateData);
      workbook.xlsx.writeBuffer().then((buffer) => {
        const blob = new Blob([buffer], { type: 'application/octet-stream' });
        // 导出 xlsx
        const linkElem = document.createElement('a');
        linkElem.target = '_blank';
        linkElem.download = `项目运营相关信息表.xlsx`;
        linkElem.href = URL.createObjectURL(blob);
        document.body.appendChild(linkElem);
        linkElem.click();
        document.body.removeChild(linkElem);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.bigbox {
  background: #ffffff;
  min-height: 100vh;
  // background-color: red;
}
.header {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 11;
  height: 50px;
  line-height: 50px;
  width: 100%;
  display: flex;
  .pageTitle {
    font-size: 16px;
    font-weight: bold;
  }
}
.sortable-row-demo .drag-btn {
  cursor: move;
  font-size: 12px;
}
.sortable-row-demo .vxe-body--row.sortable-ghost,
.sortable-row-demo .vxe-body--row.sortable-chosen {
  background-color: #dfecfb;
}
::v-deep {
  .el-button--primary {
    background-color: #165dff !important;
  }
  .vxe-table .vxe-body--row .vxe-body--column:not(:nth-child(1)) {
    border-bottom: 1px solid #e5e6eb !important;
  }
  .vxe-table .vxe-body--row .vxe-body--column:nth-child(1) {
    &::after {
      position: absolute;
      bottom: 0;
      right: 0;
      content: '';
      width: calc(100% - 84px);
      border-bottom: 1px solid #dbdada !important;
    }
  }
  .vxe-table .vxe-body--row.row--level-0 .vxe-body--column:nth-child(1) {
    &::after {
      position: absolute;
      bottom: 0;
      right: 0;
      content: '';
      width: calc(100% - 56px);
      border-bottom: 1px solid #dbdada !important;
    }
  }
  .vxe-header--column {
    background-image: none !important;
  }
  .vxe-table .vxe-body--row.row--level-1 .col_3 {
    padding-left: 10px;
  }
  .row--level-1 {
    // background-color: #f7f7f770;
  }
  .vxe-header--column {
    height: 47px;
    background: #f7f8fa;
    border-radius: 0px 0px 0px 0px;
  }
  .vxe-cell--title {
    height: 22px;
    font-size: 14px;
    font-family: PingFang SC-Medium, PingFang SC;
    font-weight: 550;
    color: #1d2129;
    line-height: 22px;
  }
}
</style>
